<template>
	<view class="details">
		<view class="detail" v-if="courseDetail">
			<image class="course-image" :src="courseDetail.avatarUrl" mode=""></image>
			<view class="course-title">
				{{courseDetail.name}}
			</view>
			<text class="course-main-category">
				<text class="category">
					{{courseDetail.categoriesName || '未分类'}}
				</text>
			</text>
			<text class="card-type-tag" v-if="courseDetail.cardType">
				<text class="tag" :style="{ backgroundColor: courseDetail.cardTypeColor }">
					{{courseDetail.categoriesName}}
				</text>
			</text>
			<view class="course-description">
				{{courseDetail.introduce || '暂无课程介绍'}}
			</view>

			<view class="course-info">
				<view class="course-info-item">
					<text class="course-info-label">
						教练:
					</text>
					<text class="course-info-value">
						{{courseDetail.aoachName || '未安排'}}
					</text>
				</view>
				<view class="course-info-item">
					<text class="course-info-label">
						时间:
					</text>
					<text class="course-info-value">
						{{formatDateTime(courseDetail.startTime)}} - {{formatTime(courseDetail.endTime)}}
					</text>
				</view>
				<view class="course-info-item">
					<text class="course-info-label">
						地点:
					</text>
					<text class="course-info-value">
						{{courseDetail.address || '未设置地点'}}
					</text>
				</view>
				<view class="course-info-item">
					<text class="course-info-label">
						人数:
					</text>
					<text class="course-info-value">
						最多{{courseDetail.maxCapacity}}人
					</text>
				</view>
				<view class="course-info-item">
					<text class="course-info-label">
						已预约:
					</text>
					<text class="course-info-value">
						{{courseDetail.quantity || 0}}人
					</text>
				</view>
				<view class="course-info-item" v-if="courseDetail.trainingContent">
					<text class="course-info-label">
						训练内容:
					</text>
					<text class="course-info-value">
						{{courseDetail.trainingContent}}
					</text>
				</view>
			</view>

			<view class="action-buttons">
				<view class="back-button" @click="historyBack">
					返回
				</view>
				<!-- 1是普通用户，2是教练 -->
				<view v-if="userinfo.status==1" class="book-button" :class="{'booked': courseDetail.booking}"
					@click="bookButton">
					{{courseDetail.booking ? '已预约' : '立即预约'}}
				</view>
			</view>
		</view>

		<!-- 加载中提示 -->
		<view class="loading" v-if="!courseDetail">
			<text>加载中...</text>
		</view>
	</view>
</template>
<script>
	import {
		getToken
	} from '@/utils/auth.js';
	export default {
		data() {
			return {
				pageId: 0,
				isBooked: false,
				courseDetail: {},
				userinfo: {}
			}
		},
		onLoad(options) {
			this.pageId = options.page;
			this.init(options.apiParams);

		},
		onShow() {
			this.wxuserget()
		},
		methods: {
			wxuserget() {
				if (!getToken()) return; // 未登录不请求			
				const data = {
					openid: getToken()
				};
				this.request('wxuserget', data, 'GET').then(res => {
					this.userinfo = res.data;
				})
			},
			init(apiParams) {
				console.log("---", apiParams)
				let that = this
				let data = {
					openid: getToken(),
					id: apiParams
				}

				this.request('gym/CoursesDetail/thisWeek', data, 'GET').then(res => {
					console.log("res:", res);
					if (res && res.code === 200 && res.data) {
						this.courseDetail = res.data;
						// 更新页面标题
						uni.setNavigationBarTitle({
							title: res.data.name || '课程详情'
						});

						// 设置是否已预约
						this.isBooked = res.data.booking || false;
					}
				})
			},
			// 格式化日期时间为 'YYYY-MM-DD HH:MM' 格式
			formatDateTime(dateTimeStr) {
				if (!dateTimeStr) return '';

				const date = new Date(dateTimeStr);
				const year = date.getFullYear();
				const month = String(date.getMonth() + 1).padStart(2, '0');
				const day = String(date.getDate()).padStart(2, '0');
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${year}-${month}-${day} ${hours}:${minutes}`;
			},

			// 格式化时间为 'HH:MM' 格式
			formatTime(dateTimeStr) {
				if (!dateTimeStr) return '';

				const date = new Date(dateTimeStr);
				const hours = String(date.getHours()).padStart(2, '0');
				const minutes = String(date.getMinutes()).padStart(2, '0');

				return `${hours}:${minutes}`;
			},

			// 格式化卡类型
			formatCardType(cardType) {
				const cardTypeMap = {
					'venue': '场地卡',
					'personal': '私教卡',
					'team': '团操卡',
					'all': '通用卡'
				};

				return cardTypeMap[cardType] || cardType;
			},
			historyBack() {
				if (this.pageId == 0) {
					uni.switchTab({
						url: "/pages/index/index"
					});
				} else {
					uni.switchTab({
						url: "/pages/about/about"
					});
				}
			},
			bookButton() {
				// 如果已经预约过，则不再弹窗
				if (this.isBooked) {
					uni.showToast({
						title: '您已预约过此课程',
						icon: 'none',
						duration: 2000
					});
					return;
				}

				let that = this;

				// 先检查权限，并明确提示用户需要授权
				uni.authorize({
					scope: 'scope.userLocation',
					success() {
						// 授权成功，直接获取位置
						that.getLocationAndBook();
					},
					fail() {
						// 授权失败
						uni.showModal({
							title: '位置权限',
							content: '预约课程需要您的位置信息。请前往设置页授权',
							confirmText: '去授权',
							cancelText: '取消',
							success(res) {
								if (res.confirm) {
									// 引导用户去开启权限
									uni.openSetting({
										success(settingRes) {
											if (settingRes.authSetting['scope.userLocation']) {
												// 用户在设置页授权了，重新获取位置
												setTimeout(() => {
													that.getLocationAndBook();
												}, 500); // 短暂延迟以确保权限生效
											} else {
												// 用户仍未授权
												uni.showToast({
													title: '需要位置权限才能预约',
													icon: 'none',
													duration: 2000
												});
											}
										}
									});
								}
							}
						});
					}
				});
			},

			// 获取位置并预约
			getLocationAndBook() {
				let that = this;

				uni.showLoading({
					title: '获取位置信息...'
				});

				// 使用更高精度的定位参数
				uni.getLocation({
					type: 'gcj02',
					isHighAccuracy: true, // 开启高精度定位
					highAccuracyExpireTime: 3000, // 高精度定位超时时间，单位ms
					success: function(res) {
						uni.hideLoading();
						const latitude = res.latitude;
						const longitude = res.longitude;
						const latitudeLongitudeUser = `${latitude},${longitude}`;

						console.log('当前位置', latitudeLongitudeUser);

						// 构造预约数据
						let data = {
							openid: getToken(),
							id: that.courseDetail.id,
							latitudeLongitudeUser: latitudeLongitudeUser
						};

						// 显示确认对话框
						uni.showModal({
							title: '预约确认',
							content: '确认要预约这节课吗？将检查您的卡类型权限。',
							cancelText: '取消',
							confirmText: '确认预约',
							success: (res2) => {
								if (res2.confirm) {
									// 用户点击确认，发起预约请求
									uni.showLoading({
										title: '预约中...'
									});

									that.request('gym/Reserve/thisWeek', data, 'GET').then(res => {
										uni.hideLoading();
										if (res && res.code === 200) {
											// 预约成功
											that.isBooked = true;
											that.courseDetail.booking = true; // 更新UI状态

											// 显示成功提示
											uni.showModal({
												title: '预约成功',
												content: '预约成功！您可以在"我的"-"约课记录"中查看。',
												showCancel: false,
												confirmText: '我知道了'
											});
										} else {
											uni.showToast({
												title: res.msg || '预约失败，请稍后重试',
												icon: 'none',
												duration: 2000
											});
										}
									}).catch(err => {
										uni.hideLoading();
										uni.showToast({
											title: '网络请求失败',
											icon: 'none',
											duration: 2000
										});
									});
								}
							}
						});
					},
					fail: function(err) {
						uni.hideLoading();
						console.error('获取位置失败', err, JSON.stringify(err));

						// 根据错误类型提供具体的错误信息
						let errorMessage = '无法获取您的位置，请检查以下问题:\n';

						if (err.errMsg && err.errMsg.indexOf('deny') > -1) {
							errorMessage += '- 位置权限被拒绝\n';
						} else if (err.errCode === 2) { // 常见的错误码，表示定位失败
							errorMessage += '- GPS定位失败，请检查手机GPS是否开启\n';
						} else if (err.errCode === 11) { // 常见的超时错误
							errorMessage += '- 定位超时，请在网络良好的环境下重试\n';
						} else {
							errorMessage += '- ' + (err.errMsg || '未知错误') + '\n';
						}

						errorMessage += '\n请重新授权位置权限并确保GPS已开启。';

						uni.showModal({
							title: '位置获取失败',
							content: errorMessage,
							showCancel: false,
							success: function() {
								// 引导用户再次尝试授权
								uni.openSetting();
							}
						});
					}
				});
			},
			bookButton1() {

				// 如果已经预约过，则不再弹窗
				if (this.isBooked) {
					uni.showToast({
						title: '您已预约过此课程',
						icon: 'none',
						duration: 2000
					});
					return;
				}
				let that = this;
				let data = {
					openid: getToken(),
					id: that.courseDetail.id,
					latitudeLongitudeUser: ''
				}
				// 显示确认对话框
				uni.showModal({
					title: '预约确认',
					content: '确认要预约这节课吗？将检查您的卡类型权限。',
					cancelText: '取消',
					confirmText: '确认预约',
					success: (res2) => {
						if (res2.confirm) {
							// 用户点击确认，模拟预约过程


							that.request('gym/Reserve/thisWeek', data, 'GET').then(res => {
								if (res && res.code === 200) {
									// 预约成功
									that.isBooked = true;
									// 显示成功提示
									uni.showModal({
										title: '预约成功',
										content: '预约成功！您可以在"我的"-"约课记录"中查看。',
										showCancel: false,
										confirmText: '我知道了',
										success: (res1) => {
											// 可以选择在这里执行其他操作
										}

									});
								} else {
									uni.showToast({
										title: res.msg,
										icon: 'none',
										duration: 2000
									});
								}
							})

						} else if (res2.cancel) {
							// 用户点击取消
							uni.showToast({
								title: '已取消预约',
								icon: 'none',
								duration: 1500
							});
						}
					}
				});
			}
		}
	}
</script>

<style lang="scss">
	@import '@/common/mixins.scss';

	// @include rounded-box(32upx);
	// @include box-sizing-padding(24upx);
	// @include flex-center(center, space-between, column);
	.details {
		width: 100vw;
		// height: 100vh;

		.detail {
			width: 686rpx;
			height: 80vh;
			margin: 5vh auto 0;
			@include rounded-box(20upx, #2a2a2a);
			@include box-sizing-padding(24upx);
			// @include flex-center(center, space-between, column);
			display: flex;
			align-items: left;
			justify-content: space-between;
			flex-direction: column;

			.action-buttons {
				width: 100%;
				@include flex-center(center, space-between);

				.back-button {
					font-size: 32rpx;
					font-weight: bold;
					width: 40%;
					height: 80rpx;
					color: #fff;
					@include rounded-box(15upx, #444);
					@include flex-center(center);
				}

				.book-button {
					font-size: 32rpx;
					font-weight: bold;
					width: 40%;
					height: 80rpx;
					@include rounded-box(15upx, #FFD700);
					color: #000000;
					@include flex-center(center);
				}
			}

			.course-info {
				width: 100%;
				background-color: #333;
				padding: 30rpx;
				border-radius: 16rpx;

				.course-info-item {
					width: 100%;
					font-size: 32rpx;
					margin-bottom: 20rpx;
					@include flex-center(center, left);

					.course-info-label {
						width: 160rpx;
						font-weight: bold;
						color: #FFD700;
					}

					.course-info-value {
						color: #e0e0e0;
					}
				}
			}

			.course-description {
				font-size: 28rpx;
				color: #e0e0e0;
			}

			.course-image {
				width: 100%;
				height: 120rpx;
			}

			.course-title {
				width: 100%;
				height: 100rpx;
				color: #FFD700;
				font-size: 36rpx;
				font-weight: bold;
				border-bottom: 4rpx solid #FFD700;
				margin: 50rpx auto 30rpx;
				@include flex-center();
			}

			.course-main-category {
				width: 100%;

				.category {
					color: #e0e0e0;
					font-size: 28rpx;
					background-color: #333;
					padding: 10rpx 20rpx;
					border-radius: 10rpx;
					border-left: 6rpx solid #FFD700;
				}

			}

			.card-type-tag {
				width: 100%;

				.tag {
					display: inline-block;
					font-size: 28rpx;
					color: #fff;
					background-color: #4caf50;
					border-radius: 10rpx;
					@include box-sizing-padding(5rpx, 10rpx);
				}

			}
		}
	}
</style>